package com.github.websocket;

import com.github.bean.ServerUser;
import com.github.manager.Manager;
import com.github.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class Handshake implements HandshakeInterceptor {
    // 在控制器或服务中添加测试
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
//        logger.info("Handshake-->response-->" + response);
//        logger.info("Handshake-->request-->" + request);
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            logger.info("Handshake-->getClientIp-->" + Utils.getClientIp(servletRequest.getServletRequest()));
        }
        String query = request.getURI().getQuery();
        String request_id = Utils.getParamValue(query, "request_id");
        String device_type = Utils.getParamValue(query, "device_type");
        String account = Utils.getParamValue(query, "account");
        ServerUser serverUser = Manager.accountUserMap.getOrDefault(account, null);
        if (serverUser == null) {
            return true;
        }
        if (device_type.equals("2") && serverUser.isCardOnline()) {
            response.setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
            return false;
        } else if (device_type.equals("3") && serverUser.isVoiceOnline()) {
            response.setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN);
            return false;
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }

}
